<template>
  <ele-page>
    <record-search :where="defaultWhere" @search="reload" />
    <ele-card :body-style="{ paddingTop: '8px' }">
      <ele-pro-table
        ref="tableRef"
        row-key="id"
        :columns="columns"
        :datasource="datasource"
        :show-overflow-tooltip="true"
        :highlight-current-row="true"
        :export-config="{ fileName: '登录日志数据' }"
        :where="defaultWhere"
        cache-key="systemLoginRecordTable"
      >
        <template #toolbar>
          <el-button type="primary" class="ele-btn-icon" @click="exportData">
            新建
          </el-button>
          <el-button type="danger" class="ele-btn-icon" @click="exportData">
            删除
          </el-button>
        </template>
        <template #loginType="{ row }">
          <el-tag
            v-if="row.loginType === 0"
            size="small"
            type="success"
            :disable-transitions="true"
          >
            登录成功
          </el-tag>
          <el-tag
            v-else-if="row.loginType === 1"
            size="small"
            type="danger"
            :disable-transitions="true"
          >
            登录失败
          </el-tag>
          <el-tag
            v-else-if="row.loginType === 2"
            size="small"
            type="info"
            :disable-transitions="true"
          >
            退出登录
          </el-tag>
          <el-tag
            v-else-if="row.loginType === 3"
            size="small"
            type="warning"
            :disable-transitions="true"
          >
            刷新TOKEN
          </el-tag>
        </template>
        <template #action="{ row }">
          <el-link type="primary" :underline="false" @click="openEdit(row)">
            修改
          </el-link>
          <el-divider direction="vertical" />
          <ele-dropdown
            :items="[
              { title: '转正', command: 'password' },
              { title: '删除', command: 'delete', danger: true, divided: true },
            ]"
            style="display: inline"
            @command="(key) => dropClick(key, row)"
          >
            <el-link type="primary" :underline="false">
              <span>更多</span>
              <el-icon :size="12" style="vertical-align: -1px; margin-left: 2px">
                <ArrowDown />
              </el-icon>
            </el-link>
          </ele-dropdown>
        </template>
      </ele-pro-table>
    </ele-card>
  </ele-page>
</template>

<script setup>
import { ref, reactive } from "vue";
import { EleMessage } from "ele-admin-plus/es";
import ExcelJS from "exceljs";
import { download } from "@/utils/common";
import { DownloadOutlined } from "@/components/icons";
import RecordSearch from "./components/record-search.vue";
import { pageLoginRecords, listLoginRecords } from "@/api/system/login-record";

defineOptions({ name: "SystemLoginRecord" });

/** 默认搜索条件 */
const defaultWhere = reactive({
  username: "",
  nickname: "",
});

/** 表格实例 */
const tableRef = ref(null);

/** 表格列配置 */
const columns = ref([
  {
    type: "selection",
    columnKey: "selection",
    width: 50,
    align: "center",
  },
  {
    type: "index",
    columnKey: "index",
    width: 50,
    align: "center",
  },
  { label: "检测项目", prop: "testItem" },
  { label: "报告号", prop: "reportNumber" },
  { label: "试验号", prop: "testNumber" },
  { label: "样品名称", prop: "sampleName" },
  { label: "规格型号", prop: "specificationModel" },
  { label: "样品数量", prop: "sampleQuantity" },
  { label: "委托单位", prop: "clientUnit" },
  { label: "委托人", prop: "clientPerson" },
  { label: "委托日期", prop: "clientDate" },
  { label: "入库交接人", prop: "inboundHandoverPerson" },
  { label: "入库交接时间", prop: "inboundHandoverTime" },
  { label: "入库接收人", prop: "inboundRecipient" },
  { label: "入库接收时间", prop: "inboundReceiveTime" },
  { label: "出库交接人", prop: "outboundHandoverPerson" },
  { label: "出库交接时间", prop: "outboundHandoverTime" },
  { label: "出库接收人", prop: "outboundRecipient" },
  { label: "出库接收时间", prop: "outboundReceiveTime" },
  { label: "退库交接人", prop: "returnHandoverPerson" },
  { label: "退库交接时间", prop: "returnHandoverTime" },
  { label: "退库接收人", prop: "returnRecipient" },
  { label: "退库接收时间", prop: "returnReceiveTime" },
  { label: "留样人", prop: "sampleKeeper" },
  { label: "留样时间", prop: "sampleKeepingTime" },
  { label: "领样交接人", prop: "sampleReceivingPerson" },
  { label: "领样交接时间", prop: "sampleReceivingTime" },
  { label: "领样接收人", prop: "sampleReceivingPerson" }, // 注意：这里假设领样接收人与交接人为同一人
  { label: "领样接收时间", prop: "sampleReceivingTime" }, // 注意：这里假设领样接收时间与交接时间为同一时间
  { label: "清除申请人", prop: "clearApplicant" },
  { label: "清除申请时间", prop: "clearApplicationTime" },
  { label: "清除批准人", prop: "clearApprover" },
  { label: "清除批准时间", prop: "clearApprovalTime" },
  {
    columnKey: "action",
    label: "操作",
    width: 128,
    align: "center",
    slot: "action",
    hideInPrint: true,
    hideInExport: true,
    fixed: "right",
  },
]);

/** 表格数据源 */
const datasource = ({ pages, where, orders, filters }) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      const records = Array.from({ length: 10 }, (_, index) => ({
        testItem: `Test Item ${index + 1}`,
        reportNumber: `Report ${index + 1001}`,
        testNumber: `Test ${index + 1}`,
        sampleName: `Sample ${index + 1}`,
        specificationModel: `Model ${(index % 3) + 1}`,
        sampleQuantity: `${index + 1}`,
        clientUnit: `Client Unit ${(index % 5) + 1}`,
        clientPerson: `Client Person ${index + 1}`,
        clientDate: new Date().toLocaleDateString(),
        inboundHandoverPerson: `Inbound Handover Person ${index + 1}`,
        inboundHandoverTime: new Date().toLocaleTimeString(),
        inboundRecipient: `Inbound Recipient ${index + 1}`,
        inboundReceiveTime: new Date().toLocaleTimeString(),
        outboundHandoverPerson: `Outbound Handover Person ${index + 1}`,
        outboundHandoverTime: new Date().toLocaleTimeString(),
        outboundRecipient: `Outbound Recipient ${index + 1}`,
        outboundReceiveTime: new Date().toLocaleTimeString(),
        returnHandoverPerson: `Return Handover Person ${index + 1}`,
        returnHandoverTime: new Date().toLocaleTimeString(),
        returnRecipient: `Return Recipient ${index + 1}`,
        returnReceiveTime: new Date().toLocaleTimeString(),
        sampleKeeper: `Sample Keeper ${index % 2 === 0 ? "Alice" : "Bob"}`,
        sampleKeepingTime: new Date().toLocaleTimeString(),
        sampleReceivingPerson: `Sample Receiving Person ${index + 1}`,
        sampleReceivingTime: new Date().toLocaleTimeString(),
        clearApplicant: `Clear Applicant ${index + 1}`,
        clearApplicationTime: new Date().toLocaleTimeString(),
        clearApprover: `Clear Approver ${index + 1}`,
        clearApprovalTime: new Date().toLocaleTimeString(),
      }));
      resolve({
        list: records,
        count: 100,
      });
    });
  });
};

/** 刷新表格 */
const reload = (where) => {
  tableRef.value?.reload?.({ page: 1, where });
};

/** 导出数据 */
const exportData = () => {
  // 请求查询全部接口
  const loading = EleMessage.loading({
    message: "请求中..",
    plain: true,
  });
  tableRef.value?.fetch?.(({ where, orders, filters }) => {
    listLoginRecords({ ...where, ...orders, ...filters })
      .then((data) => {
        const workbook = new ExcelJS.Workbook();
        const sheet = workbook.addWorksheet("Sheet1");
        sheet.addRow([
          "账号",
          "用户名",
          "IP地址",
          "设备型号",
          "操作系统",
          "浏览器",
          "操作类型",
          "备注",
          "登录时间",
        ]);
        data.forEach((d) => {
          sheet.addRow([
            d.username,
            d.nickname,
            d.ip,
            d.device,
            d.os,
            d.browser,
            ["登录成功", "登录失败", "退出登录", "刷新TOKEN"][d.loginType],
            d.comments,
            d.createTime,
          ]);
        });
        // 设置列宽
        [16, 16, 22, 22, 18, 20, 14, 16, 24].forEach((width, index) => {
          sheet.getColumn(index + 1).width = width;
        });
        // 设置样式
        sheet.eachRow({ includeEmpty: true }, (row, rowIndex) => {
          row.height = 20;
          row.eachCell({ includeEmpty: true }, (cell) => {
            cell.border = {
              top: { style: "thin" },
              left: { style: "thin" },
              bottom: { style: "thin" },
              right: { style: "thin" },
            };
            cell.alignment = {
              vertical: "middle",
              horizontal: "center",
            };
            cell.font = { size: 12, bold: rowIndex === 1 };
          });
        });
        // 下载文件
        workbook.xlsx.writeBuffer().then((data) => {
          download(data, "登录日志.xlsx");
          loading.close();
        });
      })
      .catch((e) => {
        loading.close();
        EleMessage.error(e.message);
      });
  });
};
</script>
